﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using AspNetCs.Enumerations.Up_Enum;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web;

namespace AspNetCs.Common
{
    public class UpLoad_picture
    {
        /// <summary>
        /// 上传类型判断
        /// </summary>
        /// <param name="fu"></param>
        /// <param name="fileEx"></param>
        /// <returns></returns>
        public static bool IsAllowedExtension(FileUpload fu, FileExtension_enum[] fileEx)
        {
            int fileLen = fu.PostedFile.ContentLength;
            byte[] imgArray = new byte[fileLen];
            fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
            MemoryStream ms = new MemoryStream(imgArray);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = br.ReadByte();
                fileclass = buffer.ToString();
                buffer = br.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            {
            }
            br.Close();
            ms.Close();

            foreach (FileExtension_enum fe in fileEx)
            {
                if (Int32.Parse(fileclass) == (int)fe)
                {
                    return true;
                }
            }
            return false;
        }


        /// <summary>
        /// 图片上传保存
        /// </summary>
        /// <param name="FU">FileUpload</param>
        /// <param name="cut">Cutter类</param>
        /// <param name="ErrMsg">上传成功,返回图片相对路径,路径相对于default.aspx页面,上传失败,返回失败信息</param>
        /// <returns></returns>
        public static bool UpSave(FileUpload FU, Cutter cut, out string ErrMsg)
        {
            ErrMsg = "";
            bool IsUpOk = false;
            string filename = "";
            Boolean fileOK = false;
            if (FU.HasFile)
            {

                long strLen = FU.PostedFile.ContentLength;
                if (strLen > cut.UpSize*1024)
                {
                    ErrMsg = "上传的文件不能大于" + cut.UpSize + "KB";
                    return false;
                }

                string fileExtension = System.IO.Path.GetExtension(FU.FileName).ToLower();//扩展名

                for (int i = 0; i < cut.FileType.Length; i++)
                {
                    if (fileExtension.Trim().ToLower() == cut.FileType[i].Trim().ToLower())
                    {
                        fileOK = true;
                        break;
                    }
                }

                FileExtension_enum[] fe = (FileExtension_enum[])Enum.GetValues(typeof(FileExtension_enum));

                if (fileOK && UpLoad_picture.IsAllowedExtension(FU, fe))
                {
                    string fileExt = System.IO.Path.GetExtension(FU.FileName).ToLower();


                    string uploadFilePath = "";// 服务端文件路径
                    if (cut.CreatDirectory)
                    {
                        ErrMsg = cut.UpFoler + @"/" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + @"/";//上传成功,返回文件路径,相对于根目录
                        uploadFilePath = HttpContext.Current.Server.MapPath("~") + cut.UpFoler + @"/" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + @"/";
                    }
                    else
                    {
                        ErrMsg = cut.UpFoler + @"/";//上传成功,返回文件路径,相对于根目录

                        uploadFilePath = HttpContext.Current.Server.MapPath("~") + cut.UpFoler + @"/";
                    }
                    if (!Directory.Exists(uploadFilePath))
                    {
                        Directory.CreateDirectory(uploadFilePath);
                    }
                    if (cut.IsNewFile)
                    {
                        ErrMsg += StringHelper.ReHtmlEncrypt_UP(cut.FileIsCreate + fileExt);//上传成功,返回文件路径,相对于根目录
                        filename = uploadFilePath + StringHelper.ReHtmlEncrypt_UP(cut.FileIsCreate + fileExt);
                    }
                    else
                    {
                        ErrMsg += StringHelper.ReHtmlEncrypt_UP(FU.FileName);//上传成功,返回文件路径,相对于根目录
                        filename = uploadFilePath + StringHelper.ReHtmlEncrypt_UP(FU.FileName);
                    }

                    FU.PostedFile.SaveAs(filename);

                    IsUpOk = true;
                }
                else
                {
                    ErrMsg = "上传的文件类型出错";
                }
            }
            else
            {
                ErrMsg = "请选择上传文件";
                IsUpOk = false;

            }


            return IsUpOk;
        }


        /// <summary>
        /// 创建缩略图,必须实例化Cutter类
        /// Cutter.OriginalImagePath ==源图路径（必须为物理路径）
        /// Cutter.ThumbnailPath ==缩略图路径（必须为物理路径）
        /// 
        /// *这两项必选
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static string MakeThumb(Cutter model)
        {
            string Result = "";
            if (model.OriginalImagePath == "")
            {
                return "源图路径不能为空（必须为物理路径）";
            }

            if (model.ThumbnailPath == "")
            {
                return "缩略图路径不能为空（必须为物理路径）";
            }

            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(model.OriginalImagePath);
            try
            {
                int towidth = model.SaveWidth;
                int toheight = model.SaveHeight;

                int x = 0;
                int y = 0;
                int Openw = originalImage.Width;//源图的宽
                int Openh = originalImage.Height;//源图的高

                switch (model.Types)
                {
                    case thumbType.Auto:
                        #region 按比例缩放
                        if (originalImage.Width / originalImage.Height >= model.SaveWidth / model.SaveHeight)
                        {
                            if (originalImage.Width > model.SaveWidth)
                            {
                                towidth = model.SaveWidth;
                                toheight = (originalImage.Height * model.SaveWidth) / originalImage.Width;
                            }
                            else
                            {
                                towidth = originalImage.Width;
                                toheight = originalImage.Height;
                            }


                        }
                        else
                        {
                            if (originalImage.Height > model.SaveHeight)
                            {
                                toheight = model.SaveHeight;
                                towidth = (originalImage.Width * model.SaveHeight) / originalImage.Height;
                            }
                            else
                            {
                                toheight = originalImage.Width;
                                towidth = originalImage.Height;
                            }
                        }


                        #endregion
                        break;
                    case thumbType.HW:
                        toheight = model.SaveHeight;
                        towidth = model.SaveWidth;
                        break;
                }
                string imagePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, model.ThumbnailPath);

                #region 检查当前缩略的文件夹路径是否存在,并创建

                string imagePathFolder = imagePath.Substring(0, imagePath.LastIndexOf("\\"));//缩略的文件夹路径
                if (!Directory.Exists(imagePathFolder))
                {
                    Directory.CreateDirectory(imagePathFolder);
                }
                #endregion

                if (Openw < model.SaveWidth && Openh < model.SaveHeight)
                {
                    originalImage.Save(Path.Combine(imagePathFolder, model.ThumbnailPath));
                }
                else
                {
                    //新建一个bmp图片
                    System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

                    //新建一个画板
                    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
                    //设置高质量插值法
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    //清空画布并以透明背景色填充
                    g.Clear(System.Drawing.Color.Transparent);
                    //在指定位置并且按指定大小绘制原图片的指定部分

                    g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, Openw, Openh), model.Grap);
                    //以jpg格式保存缩略图
                    bitmap.Save(model.ThumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
                    bitmap.Dispose();
                    g.Dispose();

                }
            }
            catch (Exception Ex)
            {
                Result = Ex.Message;
            }
            finally
            {
                originalImage.Dispose();
            }

            return Result;
        }

    }

    public class Cutter
    {
        #region 当前属性主要用生成缩略的参数

        private string originalImagePath = "";
        /// <summary>
        /// 源图路径（必须为物理路径）
        /// </summary>
        public string OriginalImagePath { get { return originalImagePath; } set { originalImagePath = value; } }


        private string thumbnailPath = "";
        /// <summary>
        /// 缩略图路径（物理路径）
        /// </summary>
        public string ThumbnailPath { get { return thumbnailPath; } set { thumbnailPath = value; } }


        private int savewidth = 100;
        private int saveheight = 100;
        /// <summary>
        /// 缩略图宽度,默认100
        /// </summary>
        public int SaveWidth
        {
            get { return savewidth; }
            set
            {
                if (value > 0)
                {
                    savewidth = value;
                }
            }
        }
        /// <summary>
        /// 缩略图高度,默认100
        /// </summary>
        public int SaveHeight
        {

            get { return saveheight; }

            set
            {
                if (value > 0)
                {
                    saveheight = value;
                }

            }

        }

        private GraphicsUnit grap = GraphicsUnit.Pixel;
        /// <summary>
        /// 缩略图保存的单位
        /// </summary>
        public GraphicsUnit Grap
        {
            get { return grap; }
            set { grap = value; }
        }

        private thumbType types = thumbType.Auto;
        /// <summary>
        /// 生成缩略图的方式,[默认:根据保存缩略图的高宽按比较生成]
        /// </summary>
        public thumbType Types
        {
            get { return types; }

            set
            {
                types = value;
            }

        }

        #endregion

        #region 当前属性主要用于保存上传的参数


        private string newfolder = "Uploadfiles";


        private long upsize = 200 * 1024;
        /// <summary>
        /// 文件允许上传大小[默认:200KB]
        /// </summary>
        public long UpSize
        {
            get { return upsize; }
            set
            {
                if (value > 0)
                {


                    upsize = value;
                }
            }
        }
        /// <summary>
        /// 图片上传的文件夹目录，相对于default.aspx页面[默认文件夹:“Uploadfiles/”]
        /// </summary>
        public string UpFoler
        {
            get { return newfolder; }

            set
            {
                if (value != "")
                {
                    if (value.Trim().LastIndexOf("/") == value.Trim().Length - 1)
                    {
                        newfolder = value.Substring(0, value.Trim().LastIndexOf("/"));
                    }
                    else
                    {
                        newfolder = value;
                    }


                }
            }
        }


        private bool creatDirectory = false;
        /// <summary>
        /// 是否按年月日创建文件夹[创建于上传文件夹目录之下]
        /// </summary>
        public bool CreatDirectory
        {
            get { return creatDirectory; }
            set { creatDirectory = value; }
        }


        private string[] fileType = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
        /// <summary>
        /// 文件上传的类型；格式:{ ".gif", ".png", ".jpeg", ".jpg" }
        /// </summary>
        public string[] FileType
        {
            get { return fileType; }
            set
            {
                if (value.Length > 0)
                {
                    fileType = value;
                }
            }
        }

        private string fileisCreate = DateTime.Now.ToString("yyyyMMddHHmmss");
        /// <summary>
        /// 文件名称,不包括文件类型,[默认:yyyyMMddHHmmss]
        /// </summary>
        public string FileIsCreate
        {
            get
            {
                return fileisCreate;
            }
            set
            {
                if (fileisCreate != "")
                {
                    fileisCreate = value;
                }
            }
        }

        private bool isnewfile = true;

        /// <summary>
        /// 是否生成新的文件名称,必须设置“Cutter.FileIsCreate”属性
        /// </summary>
        public bool IsNewFile
        {
            get
            {
                return isnewfile;
            }
            set
            {
                isnewfile = value;
            }
        }

        #endregion

    }



}
